'''
Created on May 8, 2012

@author: Dan Baskette
'''

import logging
from SSH import SSH
import Queue
import datetime
import datetime
import threading
import os


class Base:
    '''
    Base Class to inherit for all Classes in Project.
    Provides Logging File Access and stub method CHECK
    '''
    
    returnQueue = Queue.Queue()
    installUser = ""
    installPW = ""
    mapredUser = ""
    mapredPW = ""
    hdfsUser = ""
    hdfsPW = ""
    installSudo = ""
    kerberos = False
    
   
       
    def LogDebug(self,msg):
        logging.debug(msg)
        
    def LogInfo(self,msg):
        logging.info(msg)
        
    def LogWarning(self,msg):
        logging.warning(msg)
        
    def LogError(self,msg):
        logging.error(msg)
    
    def LogInfoCon(self,msg):
        print(msg)
        logging.info(msg)
        
    def LogErrorCon(self,msg):
        logging.error(msg)
        print(msg)


    def SSHExec(self,cmd,hostname,username,password,suppressError=False):
        '''
        Creates SSH Connection to remote Host
        '''
        execStatus = 0
        try:
            sshCon = SSH(hostname,username = username, password = password)
            (execStatus,execReturn) = sshCon.executeSt(cmd)
            sshCon.close()
            # Error in Remote Command Processing
            if (execStatus) and (suppressError == False):
                self.LogError(str(username)+":"+str(hostname)+":"+str(cmd) + ":"+str(execReturn))
            elif (execStatus) and (suppressError == True):
                self.LogDebug(str(username)+":"+str(hostname)+":"+str(cmd) + ":"+str(execReturn))

        except Exception, err:
            exception = "Trouble with SSH Connection to "+str(hostname)+":"+str(username)+":"+str(err)
            execReturn = exception
            execStatus = -1
            self.LogError(str(hostname)+":"+str(username)+":"+str(execReturn))
        self.returnQueue.put((hostname,username,execStatus,execReturn))
        self.LogDebug(str(hostname)+":"+str(username)+":"+str(execStatus)+":"+str(execReturn))
        return (execStatus,execReturn)


    def SSHPut(self,hostname,username,password,localFile,remoteFile,makeDir = False,sudo=False):
        '''
        SCP Copy from Local Host to a Remote Host
        '''   
        try:
            sshCon = SSH(hostname,username = username, password = password)
          
                
            
            
            sshCon.put(localFile,remoteFile,makeDir,sudo)
            execStatus = 0
            execReturn = "Copied "+ str(localFile)+" to "+ str(hostname)+":"+str(remoteFile)
            sshCon.close()

        except Exception, err:
            exception = "Trouble with copying "+ str(localFile) +" to "+hostname+":"+username+":"+str(err)
            
            execReturn = exception
            execStatus =-1
            self.LogError(str(hostname)+":"+str(execReturn))

        self.returnQueue.put((hostname,username,execStatus,execReturn))
        return ((execStatus,execReturn))
    
    
    
    def SSHReadFile(self,hostname,username,password,remoteFile):
        fileArray = []

        try:
            sshCon = SSH(hostname,username = username, password = password)
            fileArray = sshCon.ReadFile(remoteFile)
            execStatus = 0
            execReturn = "Got handle"
        except Exception, err:
            exception = "Trouble with SSH Connection to "+hostname+":"+username+":"+str(err)
            execReturn = exception
            execStatus = -1
            self.LogError(str(hostname)+":"+str(execReturn))
        return (execStatus,execReturn,fileArray)
    
    

    def SSHAppendFile(self,hostname,username,password,remoteFile,appendStr,sudo=False):
        try:
            sshCon = SSH(hostname,username = username, password = password)
            sshCon.AppendFile(remoteFile,appendStr,sudo)
            execStatus = 0
            execReturn = "Modified "+ str(remoteFile)+" on "+ str(hostname)+":"+str(remoteFile)
        except Exception, err:
            exception = "Trouble with SSH Connection to "+hostname+":"+username+":"+str(err)
            execReturn = exception
            execStatus = -1
            self.LogError(str(hostname)+":"+str(execReturn))

        self.returnQueue.put((hostname,username,execStatus,execReturn))
        return (execStatus,execReturn)

    def SSHCreateFile(self,hostname,username,password,remoteFile,fileText):
        try:
            sshCon = SSH(hostname,username = username, password = password)
            sshCon.CreateFile(remoteFile,fileText)
            execStatus = 0
            execReturn = "Created "+ str(remoteFile)+" on "+ str(hostname)+":"+str(remoteFile)
        except Exception, err:
            exception = "Trouble with SSH Connection to "+hostname+":"+username+":"+str(err)
            execReturn = exception
            execStatus = -1
            self.LogError(str(hostname)+":"+str(execReturn))

        self.returnQueue.put((hostname,username,execStatus,execReturn))
        return (execStatus,execReturn)



         
    def SSHGet(self,hostname,username,password,remoteFile,localFile):
        '''
        SCP Copy from Remote Host to a Local Host
        ''' 
        try:
            sshCon = SSH(hostname,username = username, password = password)
            sshCon.get(remoteFile,localFile)
            execStatus = 0
            execReturn = "Copied "+ str(localFile)+" from "+ str(hostname)+":"+str(remoteFile)
            sshCon.close()
        except Exception, err:
            exception = "Trouble with SSH Connection to "+hostname+":"+username+":"+str(err)
            execReturn = exception
            execStatus = -1
            self.LogError(str(hostname)+":"+str(execReturn))

        self.returnQueue.put((hostname,username,execStatus,execReturn))
    
    
    def ClearReturnQueue(self):
        self.returnQueue.queue.clear()

        
    def SetUsers(self,Users):
        
        '''
        method takes users aray and sets Users type appropriately
        Input:  Users Array
        Output:
            i : Install user
            m : MapRed User
            h : HDFS User
            
        Call:   Base.SetUsers(self,Users)  
        '''
        for user in Users:
            if user.role == "i":
                self.installUser = user.username
                self.installPW = user.password
                self.installSudo = user.sudo
            elif user.role == "m":
                self.mapredUser = user.username
                self.mapredPW = user.password
            elif user.role == "h":
                self.hdfsUser = user.username
                self.hdfsPW = user.password 


    def query_yes_no(self,question, default="yes"):
        valid = {"yes":True, "y":True, "ye":True, "no":False, "n":False}
        if default == None:
            prompt = " [y/n] "
        elif default == "yes":
            prompt = " [y/n] "
        elif default == "no":
            prompt = " [y/N] "
        else:
            raise ValueError("invalid default answer: '%s'" % default)

        while True:
            #print(question + prompt)
            choice = raw_input(question + prompt).lower()
            if default is not None and choice == '':
                return valid[default]
            elif choice in valid:
                return valid[choice]
            else:
                print("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
                
   
        
        
    def __init__(self):
        ''' No init'''
      